package com.project.imageinterference;

import org.apache.commons.lang3.StringUtils;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.web.client.RestTemplate;

import java.net.*;
import java.util.Enumeration;

@SpringBootApplication
@MapperScan("com.project.imageinterference.mapper")
public class ImageInterferenceApplication {

    public static void main(String[] args) throws UnknownHostException, SocketException {
        ConfigurableApplicationContext app = SpringApplication.run(ImageInterferenceApplication.class, args);

        // 获取外部IP地址
        String hostAddress = "82.157.142.158";
//        String hostAddress = getLocalHostAddress();

        // 接口地址输出配置
        ConfigurableEnvironment env = app.getEnvironment();
        String port = env.getProperty("server.port");
        String path = env.getProperty("server.servlet.context-path");
        path = StringUtils.isBlank(path) ? "" : path;

        String msg = String.format("\n------------------------------------------------------------------\n\t" +
                        "接口文档地址1: http://%s:%s%s/doc.html\n\t" +
                        "接口文档地址2: http://%s:%s%s/swagger-ui.html\n\t" +
                        "Profile(s): \t%s\n------------------------------------------------------------------",
                hostAddress, port, path, hostAddress, port, path, String.join(",", env.getActiveProfiles()));
        System.out.println(msg);
    }
    @Configuration
    public class AppConfig {
        @Bean
        public RestTemplate restTemplate() {
            return new RestTemplate();
        }
    }

    private static String getLocalHostAddress() throws SocketException, UnknownHostException {
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = networkInterfaces.nextElement();
            Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
            while (inetAddresses.hasMoreElements()) {
                InetAddress inetAddress = inetAddresses.nextElement();
                if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                    return inetAddress.getHostAddress();
                }
            }
        }
        return InetAddress.getLocalHost().getHostAddress(); // 回退到默认值
    }
}
